package com.app.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.StrUtil;
import com.app.mapper.MessageMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.util.*;
import com.app.vo.UserVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.code.kaptcha.Producer;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;


@RestController
@Controller
@RequestMapping("/api")
public class AdminUserController {
    @Autowired
    private Producer captchaProducer = null;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private MessageReadService messageReadService;

    @ResponseBody
    @RequestMapping("/captcha")
    public Result<Object> getCaptchaImage() {
        //生成文字验证码
        String text = String.format("%04d", new Random().nextInt(9999));
        //生成图片验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(99, 36);
        lineCaptcha.setBackground(Color.WHITE); // 设置背景色为白色
        // 自定义纯数字的验证码（随机4位数字，可重复）
        BufferedImage image = (BufferedImage) lineCaptcha.createImage(text);
        UUID uuid = UUID.randomUUID();
        //保存验证码到本地缓存
        CacheUtil.put(uuid.toString(), text);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", stream);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "生成验证码图片失败");
        }
        String base64 = Base64.getEncoder().encodeToString(stream.toByteArray());
        JSONObject data = new JSONObject();
        String base666 = "data:image/png;base64," + base64;
        data.put("key", uuid);
        data.put("code", base666);
        return Result.success(data);
    }

    @PostMapping("/userLogin")
    public Result<Object> userLogin(@RequestBody JSONObject json, HttpServletRequest request) {
        String pwd = json.get("pwd").toString();
        String key = json.get("key").toString();
        String code = json.get("code").toString();
        String account = json.get("account").toString();
        String salt = "gz_b";
        String pwd1 = md5Hex(pwd + salt);
        Object code1 = CacheUtil.get(key);
        if (code1 == null) {
            return Result.error(500, "验证码已失效或已过期");
        }
        if (!code1.equals(code)) {
            return Result.error(500, "验证码错误");
        }

        AdminUserModel user = adminUserService.getUserByUserName(account, pwd1);
        if (user == null) {
            return Result.error(500, "用户名或密码错误");
        }
        if (user.getRe() != null && user.getRe() == 1) {
            return Result.error(500, "存在相同账号，请联系管理员处理");
        }
        if (user.getStatus() == 1) {
            String ip = IpUtil.getIpAddress(request);
            user.setLastIp(ip);
            user.setLastLoginTime(CommonHelp.getNowTimestamp());
            adminUserService.update(user);
            String token = TokenUtils.sign(String.valueOf(user.getId()), user.getDepartmentId());
            user.setToken(token);
            return Result.success(user);
        } else {
            return Result.error(500, "该账户已失效，请联系管理员处理");
        }

    }

    //a9322c85362f9dce7c065ecd6f6cec9d
    public static void main(String[] args) {
        String salt = "gz_b";
        String pwd1 = md5Hex("123456" + salt);
        System.out.println(pwd1);

    }

    //    getAdminInfoByToken
    @GetMapping("/getAdminInfoByToken")//通过token查权限
    public Result<Object> getAdminInfoByToken(
            @RequestParam("token") String token,
            HttpServletRequest request) {
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        RoleModel roleModel = roleService.getRoleByRoleId(user.getRoles());
        if (roleModel != null) {
            String[] roleArr = roleModel.getRules().split(";");//获取字符串
            List<String> roleModelList = new ArrayList<>(Arrays.asList(roleArr));
            user.setPermissionList(roleModelList);
        }
        List<MessageModel> modelList = messageMapper.selectList(null);
        if (user.getRoles() == 2) {//二级单位
            List<MessageReadModel> messageReadModels = new ArrayList<>();
            List<MessageModel> messageModels = new ArrayList<>();
            for (int i = 0; i < modelList.size(); i++) {
                String[] split;
                if (modelList.get(i).getDepartmentId() != null) {
                    split = modelList.get(i).getDepartmentId().split(",");
                    if (Arrays.asList(split).contains(user.getDepartmentId().toString())) {
                        messageModels.add(modelList.get(i));
                    }
                }
            }
            for (int i = 0; i < modelList.size(); i++) {
                String[] split;
                if (modelList.get(i).getPersonId() != null) {
                    split = modelList.get(i).getPersonId().split(",");
                    if (Arrays.asList(split).contains(user.getPersonId().toString())) {
                        messageModels.add(modelList.get(i));
                    }
                }
            }
            for (int i = 0; i < messageModels.size(); i++) {
                MessageReadModel readByReadId = messageReadService.getReadByReadId(messageModels.get(i).getId(), user.getPersonId());
                if (readByReadId != null) {
                    messageReadModels.add(readByReadId);
                }
            }
            if (messageModels.size() > messageReadModels.size()) {
                user.setIsMessage(true);
                user.setMessageCount(messageModels.size() - messageReadModels.size());
            } else {
                user.setIsMessage(false);
                user.setMessageCount(0);
            }
        }
        if (user.getRoles() == 3) {//战士
            List<MessageReadModel> messageReadModels = new ArrayList<>();
            List<MessageModel> messageModels = new ArrayList<>();
            for (int i = 0; i < modelList.size(); i++) {
                String[] split;
                if (modelList.get(i).getPersonId() != null) {
                    split = modelList.get(i).getPersonId().split(",");
                    if (Arrays.asList(split).contains(user.getPersonId().toString())) {
                        messageModels.add(modelList.get(i));
                    }
                }
            }
            for (int i = 0; i < messageModels.size(); i++) {
                MessageReadModel readByReadId = messageReadService.getReadByReadId(messageModels.get(i).getId(), user.getPersonId());
                if (readByReadId != null) {
                    messageReadModels.add(readByReadId);
                }
                if (messageModels.size() > messageReadModels.size()) {
                    user.setIsMessage(true);
                    user.setMessageCount(messageModels.size() - messageReadModels.size());
                } else {
                    user.setIsMessage(false);
                    user.setMessageCount(0);
                }
            }
        }
        user.setPwd(null);
        return Result.success(user);
    }

    @GetMapping("/logOut")//通过token查权限
    public Result<Object> logOut(
            @RequestParam("token") String token,
            HttpServletRequest request) {
//        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
//        RoleModel roleModel = roleService.getRoleByRoleId(user.getRoles());
//        List<String> roleModelList = new ArrayList<>();
//        String[] roleArr = roleModel.getRules().split(";");//获取图片集合字符串
//        if(roleArr != null){
//            for (int i = 0; i < roleArr.length; i++) {
//                roleModelList.add(roleArr[i]);
//            }
//            user.setPermissionList(roleModelList);
//        }
        return Result.success(null);
    }

    @GetMapping("/getUserList")//角色管理分页查询
    public Result<Object> getUserList(
            @RequestParam("page") int page,
            @RequestParam("limit") int limit,
            @RequestParam("account") String account,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        Page<AdminUserModel> userModelPage = adminUserService.getPageUserList(page, limit, account);
        for (int i = 0; i < userModelPage.getRecords().size(); i++) {
            RoleModel roleModel = roleService.getRoleByRoleId(userModelPage.getRecords().get(i).getRoles());
            if (roleModel != null && roleModel.getRoleName() != null) {
                userModelPage.getRecords().get(i).setRoleName(roleModel.getRoleName());
            }
            if (userModelPage.getRecords().get(i).getDepartmentId() != null) {
                DepartmentModel departmentModel = departmentService.getDepByDepId(userModelPage.getRecords().get(i).getDepartmentId());
                if (departmentModel != null) {
                    userModelPage.getRecords().get(i).setDepartmentName(departmentModel.getName());
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (userModelPage.getRecords().get(i).getLastLoginTime() != null) {
                String LastLoginTimeText = sdf.format(userModelPage.getRecords().get(i).getLastLoginTime());
                userModelPage.getRecords().get(i).setLastLoginTimeText(LastLoginTimeText);
            }
        }
        if (userModelPage.getRecords() == null) {
            return Result.error(200, "暂无数据");
        }
        int count = (int) userModelPage.getTotal();
        List<AdminUserModel> userModelList;
        userModelList = userModelPage.getRecords();
        UserVo vo = new UserVo();
        vo.setCount(count);
        vo.setList(userModelList);
        return Result.success(vo);
    }

    @PostMapping("/insertAndUpdateUser")//    新增/修改管理员管理
    public Result<Object> insertRole(@RequestBody AdminUserModel model, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        if (model.getPwd() != null) {
            String salt = "gz_b";
            String pwd1 = md5Hex(model.getPwd() + salt);
            model.setPwd(pwd1);
        }
        try {
            if (model.getId() > 0) {
                if (StrUtil.isNotBlank(model.getPassword())) {
                    String salt = "gz_b";
                    String password = md5Hex(model.getPassword() + salt);
                    AdminUserModel userModel = adminUserService.getUserByUserId(model.getId());
                    if (!password.equals(userModel.getPwd())) {
                        return Result.error(500, "原始密码不正确");
                    }
                }
                model.setUpdateTime(CommonHelp.getNowTimestamp());
                adminUserService.update(model);
            } else {
                AdminUserModel userModel = adminUserService.getUserByName(model.getAccount());
                if (userModel != null) {
                    return Result.error(500, "管理员账号已存在");
                }
                model.setCreateTime(CommonHelp.getNowTimestamp());
                adminUserService.insert(model);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return Result.success(null);
    }

    @GetMapping("/updateUserStatus")//修改状态
    public Result<Object> updateStatus(
            @RequestParam("id") Integer id,
            @RequestParam("status") Integer status,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        AdminUserModel model = new AdminUserModel();
        model.setId(id);
        model.setStatus(status);
        adminUserService.update(model);
        return Result.success(null);
    }

    @GetMapping("/deleteById")//删除角色
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        AdminUserModel userModel = adminUserService.getUserByUserId(id);
        if (userModel == null) {
            return Result.error(500, "该管理员不存在");
        } else {
            adminUserService.delete(id);
            return Result.success(null);
        }
    }
}
